# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""

# Create your views here.
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.db.models import Count
from django.http import HttpResponseBadRequest
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import Group
from django.urls import reverse

from .forms import *
from vaues.settings import LOGIN_REDIRECT_URL
from .models import *


def login_view(request):
    form = LoginForm(request.POST or None)

    msg = None

    if request.method == "POST":

        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                if user.type == "Respondent":
                    model_set = Model.objects.filter(group__user=user.id)
                    if model_set.exists():
                        return redirect(reverse('weight', args=(model_set[0].id,)))
                    else:
                        instance_set = Instance.objects.filter(group__user=user.id)
                        return redirect(reverse('criteria_list', args=(instance_set[0].id,)))
                else:
                    return redirect(reverse(LOGIN_REDIRECT_URL))
            else:
                msg = 'Invalid credentials'
        else:
            msg = 'Error validating the form'

    return render(request, "accounts/login.html", {"form": form, "msg": msg})


def register_user(request):
    msg = None
    success = False

    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get("username")
            raw_password = form.cleaned_data.get("password1")
            user = authenticate(username=username, password=raw_password)

            msg = 'User created - please <a href="/login">login</a>.'
            success = True

        else:
            msg = 'Form is not valid'
    else:
        form = SignUpForm()

    return render(request, "accounts/register.html", {"form": form, "msg": msg, "success": success})


@login_required
@transaction.atomic
def create_mg_view(request, model_id):
    if Model.objects.filter(pk=model_id).exists():
        if not Group.objects.filter(model=model_id).exists():
            g = Group.objects.create(name=f"模型{model_id}专家")
            GroupAttr.objects.create(type='Professional', group=g, creator=request.user)
            Model.objects.filter(pk=model_id).update(group=g)
            return redirect(reverse("model_detail", args=(model_id,)))
        else:
            return HttpResponseBadRequest("用户组已存在")
    else:
        return HttpResponseBadRequest("模型不存在")


@login_required
@transaction.atomic
def create_ig_view(request, instance_id):
    instance_set = Instance.objects.filter(pk=instance_id)
    if instance_set:
        if not Group.objects.filter(instance=instance_id).exists():
            g = Group.objects.create(name=f"实例{instance_id}被试")
            GroupAttr.objects.create(type='Subject', group=g, creator=request.user)
            Instance.objects.filter(pk=instance_id).update(group=g)
            return redirect(reverse("instance_detail", args=(instance_id,)))
        else:
            return HttpResponseBadRequest("用户组已存在")
    else:
        return HttpResponseBadRequest("实例不存在")


@login_required
def group_list_view(request):
    context = {"title": "User Management",
               "segment": ["auth"],
               "page_name": "用户管理",
               "model_group": Group.objects.filter(groupattr__type="Professional",
                                                   groupattr__creator=request.user).annotate(user_count=Count('user')),
               "instance_group": Group.objects.filter(groupattr__type="Subject",
                                                      groupattr__creator=request.user).annotate(user_count=Count('user')), }
    return render(request, "accounts/group_list.html", context)


@login_required
def prof_group_list_view(request):
    context = {"title": "Professional Management",
               "segment": ["auth", 'prof'],
               "page_name": "专家管理",
               "model_group": Group.objects.filter(groupattr__type="Professional",
                                                   groupattr__creator=request.user).annotate(user_count=Count('user')),}
    return render(request, "accounts/group_list.html", context)


@login_required
def subject_group_list_view(request):
    context = {"title": "User Management",
               "segment": ["auth", 'subject'],
               "page_name": "被试管理",
               "instance_group": Group.objects.filter(groupattr__type="Subject",
                                                      groupattr__creator=request.user).annotate(user_count=Count('user')), }
    return render(request, "accounts/group_list.html", context)


@login_required
def group_detail_view(request, group_id):
    if request.method == "GET":

        context = {"segment": ["auth"],
                   "title": "User Management",
                   "page_name": "用户管理",
                   "form": CountForm}

        group = Group.objects.get(pk=group_id)
        context["group"] = group
        if group.groupattr.type == 'Subject':
            context["subject"] = User.objects.filter(groups=group_id).annotate(data_count=Count('answer'))
        elif group.groupattr.type == 'Professional':
            context["prof"] = User.objects.filter(groups=group_id).annotate(data_count=Count('parameteranswer'))

        return render(request, "accounts/user_list.html", context)

    elif request.method == "POST":

        count_form = CountForm(request.POST)
        if count_form.is_valid():
            count = count_form.cleaned_data["count"]

            u = User.objects.filter(groups=group_id).order_by('-id')
            last_count = u[0].id if u.exists() else -1
            username = [f"{group_id}_user{last_count + i}" for i in range(1, count + 1)]
            password = ['123456' for i in range(count)]

            for u, p in zip(username, password):
                user = User.objects.create_user(username=u, password=p, type="Respondent")
                user.groups.add(group_id)
                user.save()

            return redirect(reverse("group_detail", args=(group_id,)))
